var CustomControl = Class.create();
var msg_found = "Found ".fontcolor("green");
var msg_device = " devices.".fontcolor("green");
var msg_not_found = "No devices found.".fontcolor("red");
var msg_retrieve_data = "Processing retrieved data...".fontcolor("green");
CustomControl.prototype = {

	initialize: function(statusDiv, mapId, keysArray) {        
        this.status = $(statusDiv);
        this.factory = null;
        this.keys = keysArray;
        
        this.findDevicesButton = $("findDevicesButton");
        this.cancelFindDevicesButton = $("cancelFindDevicesButton");
        this.deviceSelect = $("deviceSelect");
        this.deviceInfo = $("deviceInfoText");

        this.readDataButton = $("readDataButton");
        this.cancelReadDataButton = $("cancelReadDataButton");
        this.dataString = $("dataString");


		this.progressBar = $("progressBar");
		this.progressBarDisplay = $("progressBarDisplay");

		
		this.garminController = null;
		this.intializeController();
		
		if(this.garminController && this.garminController.isPluginInitialized()) {
	        this.findDevicesButton.disabled = false;
	        this.findDevicesButton.onclick = function() {
	        	this.findDevicesButton.disabled = true;
	        	this.cancelFindDevicesButton.disabled = false;
	        	this.garminController.findDevices();
	        }.bind(this)
		}		
	},
	
	intializeController: function() {
		try {
			this.garminController = new Garmin.DeviceControl();
			this.garminController.register(this);
			
			if(this.garminController.unlock(this.keys)) {
	        	this.setStatus("Plug-in initialized.  Find some devices to get started.");
			} else {
	        	this.setStatus("The plug-in was not unlocked successfully.");
	        	this.garminController = null;
			}
		} catch (e) { this.handleException(e); }
	},

	showProgressBar: function() {
		Element.show(this.progressBar);
	},

	hideProgressBar: function() {
		Element.hide(this.progressBar);
	},

	updateProgressBar: function(value) {
		if (value) {
			var percent = (value <= 100) ? value : 100;
	    	this.progressBarDisplay.style.width = percent + "%";
		}
	},

    onStartFindDevices: function(json) {
        this.setStatus("Looking for connected Garmin devices");
    },

    onFinishFindDevices: function(json) {
    	try {
	       	this.findDevicesButton.disabled = false;
	       	this.cancelFindDevicesButton.disabled = true;
	
	        if(json.controller.numDevices > 0) {
	            var devices = json.controller.getDevices();
	            this.setStatus(msg_found + devices.length + msg_device);
	
				this.listDevices(devices);
				
		        this.cancelReadDataButton.onclick = function() {
		        	this.readDataButton.disabled = false;
		        	this.cancelReadDataButton.disabled = true;
		        	this.hideProgressBar();
		        	this.garminController.cancelReadFromDevice();
		        }.bind(this)
				
		        this.readDataButton.disabled = false;
		        this.readDataButton.onclick = function() {	
		        	this.activities = null;
		        	this.readDataButton.disabled = true;
		        	this.cancelReadDataButton.disabled = false;
		        	this.showProgressBar();
		        	
		        	try {
			        	this.garminController.readFromDevice();
		        	} catch (e) { this.handleException(e); }
		        	
		       	}.bind(this)
 
	        } else {
				this.setStatus(msg_not_found);
				this._clearHtmlSelect(this.deviceSelect);
				this.deviceSelect.disabled = true;
	        }
    	} catch (e) { this.handleException(e); }
    },
    
	onCancelFindDevices: function(json) {
    	this.setStatus("Find cancelled");
    },

	listDevices: function(devices) {
		this._clearHtmlSelect(this.deviceSelect);
		for( var i=0; i < devices.length; i++ ) {
           	this.deviceSelect.options[i] = new Option(devices[i].getDisplayName(),devices[i].getNumber());
           	if(devices[i].getNumber() == this.garminController.deviceNumber) {
           		this.deviceSelect.selectedIndex = i;
           	}
		}
   		this.deviceSelect.selectedIndex = 0;
		this.deviceSelect.onchange = function() {
			var device = this.garminController.getDevices()[this.deviceSelect.value];
			this.garminController.setDeviceNumber(this.deviceSelect.value);
		}.bind(this)
		this.deviceSelect.disabled = false;
	},

		

    onProgressReadFromDevice: function(json) {
	  	this.updateProgressBar(json.progress.getPercentage());
    	this.setStatus(json.progress);
    },
    
	onCancelReadFromDevice: function(json) {
    	this.setStatus("Read cancelled");
    },

    onFinishReadFromDevice: function(json) {
    	try {
		    this.setStatus(msg_retrieve_data);
	       	this.readDataButton.disabled = false;
	       	this.cancelReadDataButton.disabled = true;
	       	this.hideProgressBar();
	    	this.dataString.value = json.controller.gpsDataString;
	    	
	    	switch(this.fileTypeRead) {
	    		case Garmin.DeviceControl.FILE_TYPES.gpx:
	    			this.factory = Garmin.GpxActivityFactory;
	    			break;
	    		default:
	    			this.factory = null;
	    			break;
	    	}
	    		    	
	    	
    	} catch (e) { this.handleException(e); }
    },
  
    _clearHtmlSelect: function(select) {
		if(select) {
			select.options.size = 0;
		}
    },

	handleException: function(error) {
		var msg = error.name + ": " + error.message;	
		if (Garmin.PluginUtils.isDeviceErrorXml(error)) {
			msg = Garmin.PluginUtils.getDeviceErrorMessage(error);	
		}
	    this.setStatus(msg);
	    alert(msg);
	},

	setStatus: function(statusText) {
	    this.status.innerHTML = statusText;
	}
};